const express = require("express");
const { User } = require("../../models");
const router = express.Router();
const Sequelize = require("sequelize");
const { NotFoundError, UnauthorizedError } = require("../../utils/errors");
const { success, failure } = require("../../utils/responses");
const Op = Sequelize.Op;
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");

router.post("/login", async (req, res) => {
  const { email, password } = req.body;
  try {
    const { login, password } = req.body;
    if (!login) {
      throw new BadRequestError("email/username is required");
    }
    if (!password) {
      throw new BadRequestError("password is required");
    }
    const condition = {
      where: {
        [Op.or]: [{ email: login }, { username: login }],
      },
    };
    const user = await User.findOne(condition);
    if (!user) {
      throw new NotFoundError("user not found");
    }
    const isPasswordValid = bcrypt.compareSync(password, user.password);
    if (!isPasswordValid) {
      throw new UnauthorizedError("invalid password");
    }
    if (user.role !== 100) {
      throw new UnauthorizedError("user is not an admin");
    }
    const token = jwt.sign(
      { userId: user.id, role: user.role },
      process.env.JWT_SECRET,
      {
        expiresIn: "30d",
      }
    );
    return success(res, "login successful", { token });
  } catch (error) {
    return failure(res, error);
  }
});

module.exports = router;
